package com.tmxk.employee.servlet;

import com.tmxk.employee.utils.SendSms;
import com.tmxk.employee.utils.redis.RedisConn;
import org.apache.log4j.Logger;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

@WebServlet(name = "TScheduleLoginServlet",value = {"/TScheduleLoginServlet"})
public class TScheduleLoginServlet extends HttpServlet {
    private Logger logger = Logger.getLogger(TScheduleLoginServlet.class);
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 设置request、response字符编码格式,解决中文乱码
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        response.setCharacterEncoding("utf-8");
        //创建PrintWriter对象,将后台数据响应给前端
        PrintWriter out = response.getWriter();
        // 获取flag参数
        String flag = request.getParameter("flag");
        if ("getCode".equals(flag)) {
            //获取手机号
            String phone = request.getParameter("phone");
            //获取验证码
            Map<String,Object> sms = SendSms.sendSms(phone);
            if (!sms.isEmpty()) {
                //将验证码存储到redis缓存数据库中
                boolean isSendSuccess = sms.get("isSendSuccess")!= null ? (boolean)sms.get("isSendSuccess") : false;
                if (isSendSuccess) {
                    //获取验证码存储到redis
                    String verifyCode = sms.get("verifyCode")!=null ? String.valueOf(sms.get("verifyCode")) : "";
                    //调用redis
                    RedisConn redisConn = new RedisConn();
                    boolean isSave = redisConn.saveData("tmxk:travel:login:code",verifyCode,60);
                    logger.info("redis保存数据结果:" + isSave);
                }
                out.println(isSendSuccess);
            }
        }
    }
}
